package com.jsh.erp.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class AESUtil {

	/*
	  * 此处使用AES-128-CBC加密模式，key需要为16位。
	  */
	/** 密钥 */
   private static String sKey = "e3cc7538e94ce646";
   /** 偏移量(增加算法强度) */
   private static String ivParameter = "fa0c1c92739534cf";
   //公共参数
   private static String AES_ALGORITHM = "AES";
   private static String CODE_TYPE = "utf-8";
   private static String AES_TYPE = "AES/CBC/PKCS5Padding";

	// 加密
   @SuppressWarnings("restriction")
   public static String encrypt(String sSrc) throws Exception {
       Cipher cipher = Cipher.getInstance(AES_TYPE);
       byte[] raw = sKey.getBytes();
       SecretKeySpec skeySpec = new SecretKeySpec(raw, AES_ALGORITHM);
       IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());//使用CBC模式，需要一个向量iv，可增加加密算法的强度
       cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
       byte[] encrypted = cipher.doFinal(sSrc.getBytes(CODE_TYPE));
       return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码。
   }

   // 解密
   @SuppressWarnings("restriction")
   public static String decrypt(String sSrc) throws Exception {
       try {
           byte[] raw = sKey.getBytes("ASCII");
           SecretKeySpec skeySpec = new SecretKeySpec(raw, AES_ALGORITHM);
           Cipher cipher = Cipher.getInstance(AES_TYPE);
           IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
           cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
           //先用base64解密
           byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);
           byte[] original = cipher.doFinal(encrypted1);
           String originalString = new String(original, CODE_TYPE);
           return originalString;
       } catch (Exception ex) {
           return null;
       }
   }
	
}
